package session

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"sync"
)

var config sessionConfig

func InitSessionConfig(tokenName string, maxAge int, session Session) {
	config = sessionConfig{
		tokenName, maxAge, session,
	}
}

type sessionConfig struct {
	tokenName string
	maxAge    int
	session   Session
}

// SessionUtils 初始化全局工具类.
var SessionUtils = SessionManage{
	sync.Map{}, // 需要线程安全
}

type SessionManage struct {
	syncMap sync.Map
}

// Get 获取会话
func (sessionManage *SessionManage) Get(c *gin.Context) Session {
	cookie, _ := c.Cookie(config.tokenName)
	if cookie != "" {
		load, ok := sessionManage.syncMap.Load(cookie)
		if ok {
			return load.(Session)
		} else {
			return nil
		}
	} else {
		return nil
	}
}

// Set 设置会话 k-v
func (sessionManage *SessionManage) Set(c *gin.Context, k string, v interface{}) {
	session := sessionManage.Get(c)
	if session != nil {
		if session.IsExpire() {
			// 会话过期时，删除会话
			sessionManage.delete(k)
		} else {
			session.Set(k, v)
			// 更新访问时间
			session.updateLastTime()
			return
		}
	}

	// 创建会话
	newSession := config.session
	// 生成随机 uuid
	uid, _ := uuid.NewRandom()
	id := uid.String()
	newSession.generateId(id, config.maxAge)
	c.SetCookie(config.tokenName, id, 0, "/", "", false, false)
	newSession.Set(k, v)
	sessionManage.syncMap.Store(id, newSession)
}

// 删除会话
func (sessionManage *SessionManage) delete(id string) {
	sessionManage.syncMap.Delete(id)
}
